import React, { useRef, useEffect } from "react";
import type { FC } from "react";
class Particle1 {
  x: number;
  y: number;
  color: number;
  vx: number;
  vy: number;
  age: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
    this.color = (Math.random() * 255) | 0;
    this.vx = 0.5 - Math.random();
    this.vy = 0.5 - Math.random();
    this.age = Math.random() * 100;
  }

  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += 0.01;
    this.age--;
    this.color++;
  }

  draw(ctx: CanvasRenderingContext2D) {
    ctx.beginPath();
    ctx.fillStyle = `hsl(${this.color % 255}deg,50%,50%)`;
    ctx.arc(this.x, this.y, this.color % 3, 0, Math.PI * 2);
    ctx.fill();
  }
}

function draw1(
  ctx: CanvasRenderingContext2D,
  canvas: HTMLCanvasElement,
  particlesArray: Particle1[]
) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (let i = 0; i < particlesArray.length; i++) {
    const pix = particlesArray[i];
    pix.update();
    pix.draw(ctx);
    if (pix.age < 0) {
      particlesArray.splice(i, 1);
      i--; // 修正索引，因为数组长度改变了
    }
  }
}
const MouseAnimation: FC = () => {
  const canvasRef1 = useRef<HTMLCanvasElement | null>(null);
  const particlesArray = useRef<Particle1[]>([]);
  const intervalId1 = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (canvasRef1.current) {
      const ctx = canvasRef1.current.getContext("2d");
      if (ctx) {
        canvasRef1.current.width = window.innerWidth;
        canvasRef1.current.height = window.innerHeight;

        const handleMouseMove = (evt: MouseEvent) => {
          for (let i = 0; i < 10; i++) {
            particlesArray.current.push(new Particle1(evt.x, evt.y));
          }
        };

        const handleClick = (evt: MouseEvent) => {
          for (let i = 0; i < 100; i++) {
            particlesArray.current.push(new Particle1(evt.x, evt.y));
          }
        };

        window.addEventListener("mousemove", handleMouseMove);
        window.addEventListener("click", handleClick);

        intervalId1.current = setInterval(() => {
          if (ctx && canvasRef1.current) {
            draw1(ctx, canvasRef1.current, particlesArray.current);
          }
        }, 10);

        return () => {
          if (intervalId1.current) {
            clearInterval(intervalId1.current);
          }
          window.removeEventListener("mousemove", handleMouseMove);
          window.removeEventListener("click", handleClick);
        };
      }
    }
  }, []);
  return (
    <div className="MouseAnimation">
      <canvas
        ref={canvasRef1}
        style={{
          position: "fixed",
          pointerEvents: "none",
          left: 0,
          top: 0,
          width: "100%",
          height: "100%",
          zIndex: 9999,
        }}
      />
    </div>
  );
};
export default MouseAnimation;
